import dayjs from "dayjs";
import {handleTree} from "@/utils/tree";
import {message} from "@/utils/message";
// 这里给前端页面提供点击事件实现并提供一些处理函数
import {addDialog} from "@/components/ReDialog";
import {reactive, ref, onMounted, h, computed} from "vue";
import {isAllEmpty} from "@pureadmin/utils";
import {IconifyIconOnline} from "@/components/ReIcon";
import {
  getLogin2,
  getProcsDefSchema,
  queryProcsDefList,
  publishProcsDef, startProcsInstance
} from "@/api/ProcessDefListAPI";
/*import {
  MenuDTO,
  MenuRequest,
  getMenuListApi,
  addMenuApi,
  deleteMenuApi,
  getMenuInfoApi,
  updateMenuApi,
  MenuDetailDTO
} from "@/api/system/menu";*/

export function useHook() {
  const searchFormParams = reactive({
    menuName: "",
    status: null
  });

  const formRef = ref();

  const originalDataList = ref([]);
  const processDataList = ref([]);
  const defSchemaContent = ref();
  const dataList = computed(() => {
    return [...originalDataList.value];
  });
  const dataProcessList = computed(() => {
    return [...processDataList.value];
  });
  /*[
    {
      date: '2016-05-03',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Home',
    },
    {
      date: '2016-05-02',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Office',
    },
    {
      date: '2016-05-04',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Home',
    },
    {
      date: '2016-05-01',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Office',
    },
    {
      date: '2016-05-01',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Office',
    },
    {
      date: '2016-05-01',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Office',
    },
    {
      date: '2016-05-01',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Office',
    },
  ]*/
  ;
  // loadding,加载动画
  const loading = ref(true);

  const columns: TableColumnList = [
    {
      label: "流程名称",
      prop: "flowName",
      width: 200,
      align: "left"
    },
    {
      label: "流程编码",
      prop: "flowCode",
      minWidth: 260
    },
    {
      label: "当前版本",
      prop: "version",
      width: 100,
      align: "center"
    },
    {
      label: "监听器类型",
      prop: "listenerType",
      width: 160,
      align: "center"
    },
    {
      label: "图标",
      prop: "row.icon",
      minWidth: 40,
      cellRenderer: ({row}) => (
        <div class="flex justify-center">
          <IconifyIconOnline icon={row.icon}/>
        </div>
      )
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({row, props}) => (
        <el-tag size={props.size}>{row.status === 1 ? "启用" : "停用"}</el-tag>
      )
    },
    {
      label: "类型",
      prop: "isButton",
      minWidth: 100,
      formatter: ({isButton}) => (isButton ? "按钮" : "菜单")
    },

    {
      label: "创建时间",
      minWidth: 200,
      prop: "createTime",
      formatter: ({createTime}) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 320,
      slot: "operation"
    }
  ];

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  /**
   *  查询流程定义列表
   */
  async function onQueryProcsDefList() {
    // loadding,加载动画
    loading.value = true;
    // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    const {content} = await queryProcsDefList({isButton: null}).finally(() => {
      loading.value = false;
    });
    // debugger
    originalDataList.value = content.data; //content;
  }

  /**
   * 工序
   */
  async function onQueryProcessList() {
    // loadding,加载动画
    loading.value = true;
    // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    const {content} = await queryProcsDefList({isButton: null}).finally(() => {
      loading.value = false;
    });
    // debugger
    processDataList.value = content.data; //content;
  }

  async function onSearch() {
    // loadding,加载动画
    loading.value = true;
    // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    const {content} = await getLogin2({isButton: null}).finally(() => {
      loading.value = false;
    });
    loading.value = false;
    originalDataList.value = [];
  }

  /**
   * 测试用例
   * 1.添加外链跳转菜单
   * 2.添加iframe菜单  外链+内链
   * 3.添加目录
   * 4.添加一级菜单
   * 5.添加按钮
   * 6.iframe和外链跳转不允许添加按钮
   * 7.只允许目录添加子菜单
   * 8.基于目录 测试以上1~5的步骤
   * @param row dialog表单数据
   * @param done
   */
  async function handleAdd(row, done) {
    console.log("handleAdd", row);
  }

  /**
   * 测试用例
   * 1.编辑页面/目录/iframe/外链/按钮的数据
   * 2.更换父级菜单
   * 3.不允许改变类型(会导致逻辑变复杂，比如改变类型需要考虑子节点)
   * @param row
   * @param done
   */
  async function handleUpdate(row, done) {
    console.log("handleUpdate", row);
    /*await updateMenuApi(row.id, row).then(() => {
      message(`您更新了菜单:${row.menuName}`, {
        type: "success"
      });
      // 关闭弹框
      done();
      // 刷新列表
      onSearch();
    });*/
  }

  /**
   * 流程设计
   * @param title
   * @param row
   */
  async function openDesignProcess(title = "流程设计", row) {
    console.log("流程设计", title);
    // 弹框,Dialog
    // TODO 为什么声明一个formInline变量,把变量填充进去，  再给props.formInline 结果就不生效
    const procsSchema = await getProcsDefSchema({id: row.id, flowCode: row.flowCode}).finally(() => {
      loading.value = false;
    });
    addDialog({
      title: `流程设计画布`,
      props: {
        formInline: {
          id: row?.id ?? 0,
          parentId: row?.parentId ?? 0,
          menuName: row?.menuName ?? "",
          routerName: row?.routerName ?? "",
          path: row?.path ?? "",
          isButton: row?.isButton,
          permission: row?.permission ?? "",
          menuType: row?.menuType ?? undefined,
          status: row?.status ?? 1,
          meta: {rank: 0}
        },
        // higherMenuOptions: [...optionTree]
      },
      width: "60%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => {
        return (
          <div>
            <h1>这里是内容</h1>
            {procsSchema}
          </div>
        );
      },
      beforeSure: (done, {options}) => {

      }
    });
  }

  /**
   * 发起流程实例
   * @param row
   */
  async function startProcessInst(row) {
    console.log("startProcessInst");
    loading.value = true;
    const procsSchema2 = await startProcsInstance({id: row.id, flowCode: row.flowCode})
      .catch((error) => {
        loading.value = false;
        message(`发起流程实例失败：${error.errorMsg}`, {
          type: "error"
        });
      })
      .then((data) => {
        // debugger
        console.log("发起流程实例成功", data);

        if (data && !data.success) {
          message(`发起流程实例失败：${data.errorMsg}`, {
            type: "error"
          });
          return;
        }
      })
      .finally(() => {
      loading.value = false;
        /*message(`发布成功`, {
          type: "success"
        });*/
    });
  }

  /**
   * 发布流程
   * @param row
   */
  async function publishProcess(row) {
    console.log("publishProcess");
    loading.value = true;
    const procsSchema2 = await publishProcsDef({id: row.id, flowCode: row.flowCode}).finally(() => {
      loading.value = false;
      message(`发布成功`, {
        type: "success"
      });
    });
  }

  async function openDialog(title = "新增", row) {
    console.log("openDialog", title);
  }


  async function handleDelete(row) {
    console.log("handleDelete", row);
  }

  /**
   * 页面加载完成-初始化,
   */
  onMounted(() => {
    console.log("useHook mounted");
    // 查询流程定义列表
    try {
      onQueryProcsDefList();
    } catch (error) {
    }

    onQueryProcessList();
  });

  return {
    searchFormParams,
    loading,
    columns,
    dataList,
    onSearch,
    resetForm,
    openDialog,
    publishProcess,
    startProcessInst,
    openDesignProcess,
    handleDelete
  };
}
